package com.xxxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxy.dao.*;
import com.xxxy.model.ExamplePaper;
import com.xxxy.model.Question;
import com.xxxy.model.Reviewed;
import com.xxxy.model.StudentAnswer;
import com.xxxy.response.ExamplePaperResponse;
import com.xxxy.response.ReviewedQuestionResponse;
import com.xxxy.service.ExamplePaperService;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author StevenShen
 * @date 2022/3/8 21:02
 */
@Service
public class ExamplePaperServiceImpl extends ServiceImpl<ExamplePaperDao, ExamplePaper> implements ExamplePaperService {

    @Autowired
    private StudentAnswerDao studentAnswerDao;

    @Autowired
    private ExaminationPaperDao examinationPaperDao;

    @Autowired
    private ReviewedDao reviewedDao;

    @Autowired
    private QuestionDao questionDao;

    @Override
    public ExamplePaperResponse getExamplePaper(Integer examinationPaperId) {

        // 随机抽取样卷
        QueryWrapper<StudentAnswer> studentAnswerQueryWrapper = new QueryWrapper<>();
        studentAnswerQueryWrapper.eq("examination_paper_id", examinationPaperId);
        studentAnswerQueryWrapper.eq("is_example", 0);
        List<StudentAnswer> studentAnswers = studentAnswerDao.selectList(studentAnswerQueryWrapper);
        if (studentAnswers.size() == 0) {
            return null;
        }
        int number = (int) (Math.random() * studentAnswers.size());
        StudentAnswer examplePaper = studentAnswers.get(number);
        // 更新is_example
        examplePaper.setIsExample(1);
        studentAnswerDao.updateById(examplePaper);

        // 获取样卷信息
        ExamplePaperResponse response = new ExamplePaperResponse();
        response.setPaperId(examinationPaperId);
        response.setContent(examinationPaperDao.getById(examinationPaperId).getContent());
        response.setReviewedId(examplePaper.getId());

        List<ReviewedQuestionResponse> questions = new ArrayList<>();
        QueryWrapper<Reviewed> reviewedQueryWrapper = new QueryWrapper<>();
        reviewedQueryWrapper.eq("paper_id", examinationPaperId);
        List<Reviewed> revieweds = reviewedDao.selectList(reviewedQueryWrapper);

        String answerSituation = studentAnswerDao.selectById(examplePaper.getId()).getAnswerSituation();
        String[] answers = answerSituation.split(",");
        for (Reviewed reviewed : revieweds) {
            ReviewedQuestionResponse questionResponse = new ReviewedQuestionResponse();
            Question question = questionDao.selectById(reviewed.getQuestionId());
            questionResponse.setPaperId(examinationPaperId);
            questionResponse.setQuestionContent(question.getContent());
            questionResponse.setStudentAnswer(answers[reviewed.getQuestionIndex()]);
            questionResponse.setReferenceAnswer(question.getAnswer());
            questionResponse.setFullScore(reviewed.getFullScore());
            questionResponse.setQuestionIndex(reviewed.getQuestionIndex());
            questions.add(questionResponse);
        }
        response.setQuestions(questions);

        return response;

    }

    @Override
    public Boolean submit(Integer reviewedId, String questionIndex, String scores) {
        // 更新score_situation
        String[] questionIndexArray = questionIndex.split(",");
        String[] scoreArray = scores.split(",");

        StudentAnswer studentAnswer = studentAnswerDao.selectById(reviewedId);
        String scoreSituation = studentAnswer.getScoreSituation();
        String[] oldScore = scoreSituation.split(",");

        for (int i = 0, j = Integer.parseInt(questionIndexArray[0]); i < scoreArray.length; i++, j++) {
            oldScore[j] = scoreArray[i];
        }

        double totalScore = 0;
        for (String s : oldScore) {
            totalScore += Double.parseDouble(s);
        }

        String newScore = StringUtils.join(Arrays.asList(oldScore), ',');
        studentAnswer.setScoreSituation(newScore);
        studentAnswer.setTotalScore(totalScore);
        studentAnswerDao.updateById(studentAnswer);

        // 更新student_status
        Integer examinationPaperId = studentAnswer.getExaminationPaperId();
        QueryWrapper<Reviewed> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("paper_id", examinationPaperId);
        List<Reviewed> revieweds = reviewedDao.selectList(queryWrapper);

        UpdateWrapper<Reviewed> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("paper_id", examinationPaperId);
        for (Reviewed reviewed : revieweds) {
            String[] reviewedStudent = reviewed.getReviewedStudent().split(",");
            String[] studentStatus = reviewed.getStudentStatus().split(",");

            for (int i = 0; i < reviewedStudent.length; i++) {
                if (Integer.parseInt(reviewedStudent[i]) == reviewedId) {
                    studentStatus[i] = "1";
                }
            }

            reviewed.setStudentStatus(StringUtils.join(Arrays.asList(studentStatus), ','));
            reviewedDao.update(reviewed, updateWrapper);
        }
        return true;
    }
}
